/*
 * Id: $Id$
 *
 * Copyright (c) Critical Software S.A., All Rights Reserved.
 * (www.criticalsoftware.com)
 *
 * This software is the proprietary information of Critical Software S.A.
 * Use is subject to license terms.
 *
 * Last changed on : $Date$
 * Last changed by : $Author$
 */
package com.m2rt.queuenumber.domain.repository;

import com.m2rt.queuenumber.domain.entities.Office;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

/**
 * Description.
 *
 * @author :    Marco Ribeiro
 * @version :   $Rev$
 */
@Repository
public class OfficeRepositoryImpl implements OfficeRepository {

    @PersistenceContext
    private EntityManager entityManager;


    public List<Office> findByName(String name) {

        Query query = entityManager.createQuery("SELECT s FROM Office s WHERE s.name LIKE ?1");
        query.setParameter(1, name + "%");
        return query.getResultList();
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public Office save(Office service) {
        entityManager.persist(service);
        return service;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void deleteAll() {
        entityManager.createQuery("DELETE FROM Office ").executeUpdate();
    }

    @Override
    public boolean exists(Long id) {
        return entityManager.createQuery("SELECT o FROM Office o WHERE o.id = ?1").setParameter(1, id)
                .getSingleResult() != null;
    }

    @Override
    public List<Office> listOffices() {
        return entityManager.createQuery("SELECT s FROM Office s ORDER BY s.name").getResultList();
    }
}